package jvm;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicStampedReference;

/**
 * @author Europa
 * @create 2020-06-02 16:52
 */
public class ABADemo {

    public static void main(String[] args) {
        // 注意超出Integer缓存范围可能会出错
        AtomicStampedReference<Integer> reference = new AtomicStampedReference<Integer>(1, 1);

        int one = 1;
        int two = 2;
        new Thread(() -> {
            int stamp = reference.getStamp();
            System.out.println("stamp = " + stamp);
            try {
                TimeUnit.SECONDS.sleep(2L);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            reference.compareAndSet(one, two, stamp, stamp + 1);
            int stamp1 = reference.getStamp();
            System.out.println("stamp1 = " + stamp1);
            boolean compareAndSet1 = reference.compareAndSet(two, one, stamp1, stamp1 + 1);
            System.out.println("compareAndSet1 = " + compareAndSet1);
            int stamp2 = reference.getStamp();
            System.out.println("stamp2 = " + stamp2);
        }, "a").start();

        new Thread(() -> {
            int getStamp = reference.getStamp();
            System.out.println("getStamp = " + getStamp);
            try {
                TimeUnit.SECONDS.sleep(2L);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            boolean compareAndSet2 = reference.compareAndSet(one, 6, getStamp, getStamp + 1);
            System.out.println("compareAndSet2 = " + compareAndSet2);
            int getStamp1 = reference.getStamp();
            System.out.println("getStamp1 = " + getStamp1);
        }, "b").start();
    }
}
